﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using System.Reflection;

namespace Htse.Blue.Helpers
{
	public static class MemberExpressionHelper
	{
		public static MemberExpression GetMemberExpression(this Expression expression)
		{
			LambdaExpression lambda = expression as LambdaExpression;
			if (lambda == null)
				throw new ArgumentNullException("method");

			MemberExpression memberExpr = null;

			if (lambda.Body.NodeType == ExpressionType.Convert)
			{
				memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
			}
			else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
			{
				memberExpr = lambda.Body as MemberExpression;
			}
			
			if (memberExpr == null)
				throw new ArgumentException("method");

			return memberExpr;
		}

		public static string ExtractPropertyName(this MemberExpression memberExpression)
		{
			string result = string.Empty;

			if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess)
			{
				result += string.Format(
					"{0}.",
					(memberExpression.Expression as MemberExpression).ExtractPropertyName());
			}

			result += memberExpression.Member.Name;

			return result;
		}

		public static object ExtractPropertyValue<T>(this MemberExpression memberExpression, object item)
		{
			PropertyInfo pi = null;
			object result = item;

			if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess)
			{
				result = (memberExpression.Expression as MemberExpression).ExtractPropertyValue<T>(result);
			}

			pi = memberExpression.Expression.Type.GetProperty(memberExpression.Member.Name);

			result = pi.GetValue(result, null) ?? string.Empty;

			return result;
		}
	}
}
